package com.region.integral.common_user.obtain.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

import com.region.integral.common_user.obtain.dao.IIntegralCommentWeiBo;
import com.region.integral.common_user.obtain.vo.IntegralData;
import com.region.integral.common_user.pojo.CUIEntity;
import com.region.integral.common_user.xml.Regulation;
import com.region.integral.common_user.xml.dto.CommentGoods;
import com.region.integral.common_user.xml.dto.CommentWeiBo;
import com.region.integral.exception.IntegralException;
import com.region.integral.hibernate.BaseHibernate;
import com.region.integral.util.ExceptionPropertiesUtil;
import com.region.integral.util.IntegralExceptionConstants;
import com.region.integral.util.IntegralConstants;
import com.region.integral.util.RegulationUtil;
import com.region.integral.util.XMLRegulationUtil;
@Component("iCommentWeiBo")
public class IntegralCommentWeiBoImpl extends BaseHibernate implements
		IIntegralCommentWeiBo {

	@Override
	public void commentWeiBo(int userid ,IntegralData integralData) throws IntegralException {
		
		CUIEntity cuiEntity = getCUIEntity(userid);
		if (cuiEntity != null) {
			int commentWeiBoNum = cuiEntity.getCommentWeiBoNum();
			// 已换另一种实现方式
			/*
			 * int commentWeiBoNum = cuiEntity.getCommentWeiBoNum(); //获取规则
			 * String ruleIntegral = RegulationUtil
			 * .getRuleIntegral(IntegralRuleConstants.COMMENT_WEIBO_TEN);
			 * String[] rateAndIntegral = ruleIntegral.split(","); int rate =
			 * Integer.parseInt(rateAndIntegral[0]); int integral =
			 * Integer.parseInt(rateAndIntegral[1]); //判断频率 if(commentWeiBoNum
			 * != 0 && commentWeiBoNum % rate == 0){ int currIntegral =
			 * cuiEntity.getCurrIntegral(); int totalIntegral = currIntegral +
			 * integral; cuiEntity.setCurrIntegral(totalIntegral);
			 * cuiEntity.setCommentWeiBoNum(commentWeiBoNum + 1);
			 * hibernateTemplate.update(cuiEntity); return true;
			 */

			// 获取积分规则
			Regulation regulation = XMLRegulationUtil.unmarshaller();
			List<CommentWeiBo> commentWeiBos = regulation.getCommentweibo();
			for (CommentWeiBo commentWeiBo : commentWeiBos) {
				if (commentWeiBoNum != 0 && commentWeiBoNum % commentWeiBo.getRate() == 0) {
					int currIntegral = cuiEntity.getCurrIntegral();
					int maxIntegral = cuiEntity.getMaxIntegral();
					int totalIntegral = currIntegral+ commentWeiBo.getIntegral();
					if (maxIntegral < totalIntegral) {
						cuiEntity.setMaxIntegral(totalIntegral);
					}
					cuiEntity.setCurrIntegral(totalIntegral);
					integralData.setSuccee(true);
					integralData.setObtainIntegral(commentWeiBo.getIntegral());
					hibernateTemplate.update(cuiEntity);
				}
			}
			cuiEntity.setCommentWeiBoNum(commentWeiBoNum + 1);
			hibernateTemplate.update(cuiEntity);
		} 
	}

}
